package com.david;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ReferenceCountUtil;

/**
 * @ClassName NettyClient
 * @Description TODO
 * @Authod 大伟
 * @Date 2021/3/1 1:25
 * @Version v1.0
 **/
public class NettyClient {
    private void clientStart() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ClientHander());
                    }
                });
        try{

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new NettyClient().clientStart();
    }

    class ClientHander extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
           try{
               ByteBuf byteBuf = (ByteBuf) msg;
               System.out.println(byteBuf.toString());
           }finally {
               ReferenceCountUtil.release(msg);
           }
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            final ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer("hellonetty".getBytes()));
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    System.out.println("数据已经送达！！！");
                }
            });
        }
    }
}
